<button type="button" class="layui-btn layui-btn-danger" onclick="batchDeleteQuestions()">批量删除</button>
<button type="button" class="layui-btn" onclick="addQuestion()">新增题目</button>
<input type="text" name="studentName" id="key-word" placeholder="请输入关键字进行搜索" class="layui-input">
<button type="button" class="layui-btn layui-btn-normal" onclick="search()">搜索</button>
<table id="question-info" lay-filter="question-info"></table>


<div id="add-question" style="display: none;">
	<form lay-filter="add-question-form" id="add-question-form">
		<div class="layui-form-item">
			<label class="layui-form-label">题目</label>
			<div class="layui-input-block">
				<div id="add-questionContent" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">A、</label>
			<div class="layui-input-block">
				<div id="add-answerA" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">B、</label>
			<div class="layui-input-block">
				<div id="add-answerB" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">C、</label>
			<div class="layui-input-block">
				<div id="add-answerC" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">D、</label>
			<div class="layui-input-block">
				<div id="add-answerD" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">解析</label>
			<div class="layui-input-block">
				<div id="add-analyse" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">正确答案</label>
			<div class="layui-input-block">
				<label class="layui-form-label">A.
					<input type="radio" name="addCorrAnswer" value="A" title="A">
				</label>

				<label class="layui-form-label">B.
					<input type="radio" name="addCorrAnswer" value="B" title="B">
				</label>

				<label class="layui-form-label">C.
					<input type="radio" name="addCorrAnswer" value="C" title="C">
				</label>

				<label class="layui-form-label">D.
					<input type="radio" name="addCorrAnswer" value="D" title="D">
				</label>
			</div>
		</div>
	</form>
</div>

<div id="edit-question" style="display: none;">
	<form class="layui-form" lay-filter="edit-question-form">
		<div class="layui-form-item">
			<label class="layui-form-label">题目</label>
			<div class="layui-input-block" id="questionContent">
				<div id="edit-questionContent" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">A、</label>
			<div class="layui-input-block" id="answerA">
				<div id="edit-answerA" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">B、</label>
			<div class="layui-input-block" id="answerB">
				<div id="edit-answerB" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">C、</label>
			<div class="layui-input-block" id="answerC">
				<div id="edit-answerC" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">D、</label>
			<div class="layui-input-block" id="answerD">
				<div id="edit-answerD" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">解析</label>
			<div class="layui-input-block" id="analyse">
				<div id="edit-analyse" type="text/plain" style="height:100px;">

				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">正确答案</label>
			<div class="layui-input-block">
				<div class="layui-input-block" id="edit-question-radio">
					<input type="radio" name="editCorrAnswer" value="A" title="A">
					<input type="radio" name="editCorrAnswer" value="B" title="B">
					<input type="radio" name="editCorrAnswer" value="C" title="C">
					<input type="radio" name="editCorrAnswer" value="D" title="D">
				</div>
			</div>
		</div>
	</form>
</div>

<script type="text/javascript" src="../../ueditor1_4_3_1-utf8-jsp/utf8-jsp/ueditor.config.js"></script>
<script type="text/javascript" src="../../ueditor1_4_3_1-utf8-jsp/utf8-jsp/ueditor.all.js"></script>
<script type="text/javascript" src="../../ueditor1_4_3_1-utf8-jsp/utf8-jsp/lang/zh-cn/zh-cn.js"></script>
<script>
	layui.use(["form", "table", "layer"], function (form, table, layer) {
		//全局变量
		var keyWord = "";
		//初始加载是没有关键字搜索的
		if ("" == keyWord) {
			tableLoad(keyWord);
		}
		//封装渲染表格
		function tableLoad(keyWord) {
			table.render({
				elem: '#question-info',
				height: 460,
				url: serverPath + "/questions?q=" + keyWord,
				headers: {
					"auth-token": getToken()
				},
				//res 即为原始返回的数据
				parseData: function (res) {
					return {
						"code": res.data.code,
						"count": res.data.count,
						"data": res.data.data
					};
				},
				page: true,
				page: {
					limit: 5,
					limits: [5, 10, 15, 20]
				},
				cols: [
					[{
						field: '',
						title: '',
						align: "center",
						type: "checkbox"
					}, {
						field: 'questionId',
						title: '',
						align: "center",
						hide: true
					},
					{
						field: 'questionContent',
						title: '题目',
						align: "center"
					},
					{
						field: 'answerA',
						title: '答案A',
						align: "center"
					},
					{
						field: 'answerB',
						title: '答案B',
						align: "center"
					},
					{
						field: 'answerC',
						title: '答案C',
						align: "center"
					},
					{
						field: 'answerD',
						title: '答案D',
						align: "center"
					},
					{
						field: 'analyse',
						title: '答案解析',
						align: "center"
					},
					{
						field: 'correctAnswer',
						title: '正确答案',
						align: "center"
					},
					{
						field: '',
						title: '操作',
						align: "center",
						templet: function (row) {
							return `&nbsp;&nbsp;<button type="button" class="layui-btn layui-btn-normal" lay-event="editQuestion">修改</button>
		                    <button type="button" class="layui-btn layui-btn-danger" lay-event="deleteQuestion">删除</button>`;
						}
					}
					]
				],
				done: function (res, curr, count) {
					if (curr > 1 && null == res.data) {
						curr = curr - 1;
						table.reload('question-info', {
							//设定异步数据接口的额外参数，任意设
							where: {},
							page: {
								curr: curr
							}
						});
					}
				}
			});
		}

		//搜索题目 $("#key-word").val("")
		window.search = function () {
			//获取输入的关键字
			keyWord = $("#key-word").val();
			if ("" == keyWord) {
				layer.alert("输入不能为空...")
				return;
			}
			//表格重新渲染
			tableLoad(keyWord);
		}

		//新增问题
		window.addQuestion = function () {
			// //重置表单
			// resetForm();
			//实例化编辑器
			var a_add, b_add, c_add, d_add, e_add, f_add;
			layer.open({
				type: 1,
				title: "新增问题",
				area: ["1000px", "700px"],
				content: $("#add-question"),
				btn: ['确认', "取消"],
				btnAlign: 'c',
				yes: function (index, layero) {
					//判断题目的各种元素不能为空
					var flag = questionInfoIsNotNull(a_add, b_add, c_add, d_add, e_add, f_add);
					if (flag) {
						//正确答案
						var correctAnswer =  $("input[type='radio'][name='addCorrAnswer']:checked").val();
						if (undefined == correctAnswer) {
							layer.alert("请设置该题的正确答案");
							return;
						}
						//获取所有的信息
						var params = getQuestionAllInfo(a_add, b_add, c_add, d_add, e_add, f_add, correctAnswer);
						console.log(params);
						//axios发送请求新增题目
						axios.post(serverPath + "/questions", params, {
							headers: {
								"auth-token": getToken()
							}
						})
							.then(function (response) {
								//成功后关闭上一个弹窗
								layer.close(index);
								//表格重新渲染
								table.reload("question-info");
								layer.confirm(response.data.data, function () {
									//关闭所有弹窗
									layer.closeAll();
								})
							})
							.catch(function (error) {
								layer.alert(error.response.data.error);
							});
					}
				},
				btn2: function (index, layero) {
					layer.confirm("是否退出?", function () {
						layer.closeAll();
					})
					return false;
				},
				success: function () {
					a_add = UE.getEditor('add-questionContent');
					b_add = UE.getEditor('add-answerA');
					c_add = UE.getEditor('add-answerB');
					d_add = UE.getEditor('add-answerC');
					e_add = UE.getEditor('add-answerD');
					f_add = UE.getEditor('add-analyse');
					//更新渲染form
					form.render();
				}
			});

		};
		table.on('tool(question-info)', function (obj) {
			//获得当前行数据
			var data = obj.data;
			//获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
			var layEvent = obj.event;
			//该题编号
			var questionId = data.questionId;
			//正确答案
			var correctAnswer = data.correctAnswer;
			//实例ueditor
			a_edit = UE.getEditor('edit-questionContent');
			b_edit = UE.getEditor('edit-answerA');
			c_edit = UE.getEditor('edit-answerB');
			d_edit = UE.getEditor('edit-answerC');
			e_edit = UE.getEditor('edit-answerD');
			f_edit = UE.getEditor('edit-analyse');
			//编辑题目
			if (layEvent === 'editQuestion') {
				layer.open({
					type: 1,
					title: "修改问题",
					area: ["1000px", "700px"],
					content: $("#edit-question"),
					btn: ['确认', "取消"],
					btnAlign: 'c',
					yes: function (index, layero) {
						//判断是否为空
						var flag = questionInfoIsNotNull(a_edit, b_edit, c_edit, d_edit, e_edit, f_edit);
						if (flag) {
							var data_form = form.val("edit-question-form");
							//正确答案
							var correctAnswer = data_form.editCorrAnswer;
							if (undefined == correctAnswer) {
								layer.alert("请设置该题的正确答案");
								return;
							}
							//获取所有的信息
							var params = getQuestionAllInfo(a_edit, b_edit, c_edit, d_edit, e_edit, f_edit, correctAnswer)
							//加上该题目的编号
							params.questionId = questionId;

							var userId = parseInt(instance.defaults.userId);
							console.log(params)
							// axios发送请求修改题目
							axios.put(serverPath + "/questions/" + userId, params, {
								headers: {
									"auth-token": getToken()
								}
							}).then(function (response) {
								//成功后关闭上一个弹窗
								layer.close(index);
								layer.confirm(response.data.data, function () {
									//表格重新渲染
									table.reload("question-info");
									//关闭所有弹窗
									layer.closeAll();
								})
							}).catch(function (error) {
								layer.alert(error.response.data.error);
							});
						}
					},
					btn2: function (index, layero) {
						layer.confirm("是否退出?", function () {
							destroyUeditor();
							layer.closeAll();
						})
						return false;
					},
					success: function () {
						//将值设置进ueditor
						setUeValue(a_edit, data.questionContent);
						setUeValue(b_edit, data.answerA);
						setUeValue(c_edit, data.answerB);
						setUeValue(d_edit, data.answerC);
						setUeValue(e_edit, data.answerD);
						setUeValue(f_edit, data.analyse);
						//加载选项
						$("#edit-question-radio").find("input[value = '" + correctAnswer + "']").attr("checked", "checked");
						form.render();
					},
					cancel: function (index, layero) {
						layer.confirm('确定要关闭么', function () {
							destroyUeditor();
							layer.closeAll();
						})
						return false;
					}
				});
			}
			//删除单个题目
			if (layEvent === 'deleteQuestion') {
				layer.confirm('是否要删除吗?', function (index) {
					//删除对应行（tr）的DOM结构，并更新缓存
					obj.del();
					layer.close(index);
					//向服务端发送删除指令
					//deleteAny该方法在common.js中
					deleteAny(questionId, (serverPath + "/questions"), "question-info");
				});
			}
		});

	});

	//批量删除问题
	window.batchDeleteQuestions = function () {
		var checkStatus = table.checkStatus('question-info');
		var checkData = checkStatus.data;
		var questionIds = $.map(checkData, function (obj) {
			console.log(obj)
			return obj.questionId;
		});
		if (questionIds.length < 2) {
			layer.alert("请至少选择两条数据");
			return;
		}
		deleteAny(questionIds, (serverPath + "/questions"), "question-info");
		table.reload("question-info");
	};

	//重置表单
	function resetForm() {
		document.getElementById("add-question-form").reset();
	}

	//获取题目的所有信息 getContentTxt()纯文本
	function getQuestionAllInfo(a, b, c, d, e, f, correctAnswer) {
		var params = {}
		params.questionContent = a.getContent();
		params.answerA = b.getContent();
		params.answerB = c.getContent();
		params.answerC = d.getContent();
		params.answerD = e.getContent();
		params.analyse = f.getContent();
		params.correctAnswer = correctAnswer;
		return params;
	}

	//判断题目中的各种元素不能为空
	function questionInfoIsNotNull(a, b, c, d, e, f) {
		var flag = false;
		if (!a.hasContents()) {
			layer.alert("题目的内容不能为空!");
			return;
		}
		if (!b.hasContents()) {
			layer.alert("选项A的内容不能为空!");
			return;
		}
		if (!c.hasContents()) {
			layer.alert("选项B的内容不能为空!");
			return;
		}
		if (!d.hasContents()) {
			layer.alert("选项C的内容不能为空!");
			return;
		}
		if (!e.hasContents()) {
			layer.alert("选项D的内容不能为空!");
			return;
		}
		if (!f.hasContents()) {
			layer.alert("题目分析的内容不能为空!");
			return;
		}
		flag = true;
		return flag;
	}

	function apendHtml() {
		$("#questionContent").html(`<div id="edit-questionContent" type="text/plain" style="height:100px;"></div>`);
		$("#answerA").html(`<div id="edit-answerA" type="text/plain" style="height:100px;"></div>`);
		$("#answerB").html(`<div id="edit-answerB" type="text/plain" style="height:100px;"></div>`);
		$("#answerC").html(`<div id="edit-answerC" type="text/plain" style="height:100px;"></div>`);
		$("#answerD").html(`<div id="edit-answerD" type="text/plain" style="height:100px;"></div>`);
		$("#analyse").html(`<div id="edit-analyse" type="text/plain" style="height:100px;"></div>`);
	}

	function deleteHtml() {
		$("#questionContent").html('');
		$("#answerA").html('');
		$("#answerB").html('');
		$("#answerC").html('');
		$("#answerD").html('');
		$("#analyse").html('');
		$("textarea").remove();
	}
	function destroyUeditor() {
		UE.getEditor('edit-questionContent').destroy();
		UE.getEditor('edit-answerA').destroy();
		UE.getEditor('edit-answerB').destroy();
		UE.getEditor('edit-answerC').destroy();
		UE.getEditor('edit-answerD').destroy();
		UE.getEditor('edit-analyse').destroy();
		deleteHtml();
		apendHtml();
	}
</script>